package controllers;

import java.util.Date;

import models.User;
import play.mvc.Http.Context;
import play.mvc.Result;
import play.mvc.Security.Authenticator;

/*
 * Security
 * Session and session timeout
 * Author: Talasbek Assem
 */

public class Secured extends Authenticator {

	@Override
	public String getUsername(Context ctx) {
		if(ctx.session().get("uname") == null || User.find.where().eq("username", ctx.session().get("uname")).findRowCount() == 0)
			return null;
		System.out.println(true);
		String prevTick = ctx.session().get("userTime");
		if(prevTick != null && !prevTick.equals(""))
		{
			System.out.println(true);
			long prevT = Long.valueOf(prevTick);
			long currentT = new Date().getTime();
			long timeOut = 30 * 1000 * 60;
			if((currentT - prevT) > timeOut)
			{
				System.out.println(true);
				ctx.session().clear();
				return null;
			}
		}
		String tickString = Long.toString(new Date().getTime());
		ctx.session().put("userTime", tickString);
		return ctx.session().get("uname");
	}
	
/*	
 * Cookie doesn't work
 * 
	@Override
	public String getUsername(Context ctx) {
		Iterable<Cookie> it = ctx.response().cookies();
		String username = null;
		int i = 0;
		for(Cookie c : it)
		{
			if("uname".equals(c.name()))
			{
				username = c.value();
				i = new Finder<Long, User>(Long.class, User.class).where().eq("username", username).findRowCount();
			}
		}
		return i==0?null:username;
	}
*/
	@Override
	public Result onUnauthorized(Context ctx) {
		return redirect(routes.Authentication.login());
	}
}